const WXAPI = require('apifm-wxapi')
const app = getApp();
const WxParse = require('../../wxParse/wxParse.js');
import ApifmShare from '../../template/share/index.js';
const CONFIG = require('../../config.js')
const AUTH = require('../../utils/auth')
const SelectSizePrefix = "选择："
const SETGOODS = require('../../utils/setgoos.js');

let videoAd = null; // 视频激励广告

Page({
  data: {
    goodsDetail: {},
    hasMoreSelect: false,
    selectSize: SelectSizePrefix,
    selectSizePrice: 0,
    totalScoreToPay: 0,
    shopNum: 0,
    hideShopPopup: true,
    buyNumber: 1,
    buyNumMin: 1,
    buyNumMax: 0,

    propertyChildIds: "",
    propertyChildNames: "",
    canSubmit: false, //  选中规格尺寸时候是否允许加入购物车
    shopCarInfo: {},
    shopType: "addShopCar", //购物类型，加入购物车或立即购买，默认为加入购物车
    selItem:{},//默认选中规格
    isPhoneX:false,
    pinDanList: [],
    hidePindan: true,
    showAuthBtn: false,
    groupNo: "",
    total: 0,
    pageSize: 0
  },
  // 微信授权
  getWeChatInfo(e) {
    const that = this
    wx.getSetting({
      success: res => {
        if (res.authSetting['scope.userInfo']) {
          this.setData({
            showAuthBtn: false
          })
          wx.login({
            success: loginres => {
              wx.setStorage({
                key: 'userInfo',
                data: e.detail.userInfo
              })
              WXAPI.login_wx(loginres.code).then(res => {
                wx.setStorageSync('token', res.data.tokenStr)
                WXAPI.updateUser({
                  nickName: e.detail.userInfo.nickName,
                  headUrl: e.detail.userInfo.avatarUrl,
                  gender: e.detail.userInfo.gender,
                }).then(res => {})
                // 判断是否需要弹出规格弹层或者立即开团
                if (this.data.buyType && this.data.buyType === 'tuan') {
                  // 立即开团
                  this._pintuanCommonFunc()
                } else {
                  // 弹出规格
                  this.setData({
                    shopType: "tobuy"
                  });
                  this.bindGuiGeTap()
                }
              })
            }
          })
        } else {
          // 拒绝授权
          this.setData({
            showAuthBtn: false
          })
        }
      }
    })
  },
  // 拼团列表
  findPintuanList(id) {
    console.log(this.data.groupNo)
    WXAPI.findByItemNoAndGroupNo({
      itemNo: id,
      groupNo: this.data.groupNo
    }).then(res => {
      let pindanArr = res.data.list
      for (let item of pindanArr) {
        // 获取订单截止时间戳，并与当前时间戳相减
        item.time = Date.parse(item.endTime) - Date.parse(new Date());
        item.num = item.targetNum - item.actNum
      }
      this.setData({
        pinDanList: pindanArr,
        total: res.data.total,
        pageSize: res.data.pageSize
      })
    })
  },
  // 发起拼团
  _pintuanCommonFunc() {
    WXAPI.createGroup({
      itemNo: this.data.itemNo
    }).then(function(res) {
      const code = res.data // 开团编号
      if (res.retCode !== "200") {
        wx.showToast({
          title: res.retMsg,
          duration: 2000,
          icon: "none"
        })
        return
      }
      wx.navigateTo({
        url: `/pages/kaituan/index?code=${code}`,
      })
    })
  },
  toPingtuan() {
    const token = wx.getStorageSync('token') || ""
    this.setData({
      buyType: "tuan" // 发起拼团
    })
    // 这里要判断没有登陆还是登陆已经过期
    if (!token) {
      // 未登录
      this.setData({
        showAuthBtn: true
      })
      return
    }
    AUTH.checkHasLogined().then(isLogined => {
      if (!isLogined) {
        wx.login({
          success: loginres => {
            WXAPI.login_wx(loginres.code).then(res => {
              wx.setStorageSync('token', res.data.tokenStr)
              this._pintuanCommonFunc()
            })
          }
        })
      } else {
        const token = wx.getStorageSync('token') || ""
        if (!token) {
          this.setData({
            showAuthBtn: true
          })
          return
        }
        this._pintuanCommonFunc()
      }
    })

  },
  async onLoad(e) {
    // 保留从开团待分享页面进来带过来得开团编号
    if (e.groupNo && e.groupNo !== "undefined") {
      this.setData({
        groupNo: e.groupNo
      })
    }
    ApifmShare.init(this)
    if (e && e.scene) {
      const scene = decodeURIComponent(e.scene) // 处理扫码进商品详情页面的逻辑
      if (scene) {
        e.id = scene.split(',')[0]
        wx.setStorageSync('referrer', scene.split(',')[1])
      }
    }
    console.log('e-0-',e)
    // this.data.goodsId = e.id
    // this.data.kjJoinUid = e.kjJoinUid
    
    const that = this;
    if (e && e.id && e.shopNo){
      if (e && e.shopNo) {
        // app.globalData.shopNo = e.shopNo;
        app.setShopNo(e.shopNo);
      } else {
        app.setShopNo();
      }
    }
    this.setData({
      goodsId: e.id,
      // kjJoinUid: e.kjJoinUid,
      shopNum: app.globalData.goodsNo,
    })
    wx.getStorage({
      key: 'shopCarInfo',
      success: function (res) {
        let list = res.data;
        that.setData({
          shopCarInfo: res.data,
          curuid: wx.getStorageSync('uid')
        });
      }
    })
    if (app.globalData.isPhoneX){
      this.setData({
        isPhoneX:true,
      })
    }else{
      this.setData({
        isPhoneX: false,
      })
    }
  },
  onShow (){
    // init
    this.setData({
      buyType: "",
      shopNo: ""
    })
    this.getGoodsDetailAndKanjieInfo(this.data.goodsId)
    this.findPintuanList(this.data.goodsId)
  },
  handlePindan() {
    this.setData({
      hidePindan: false
    })
  },
  // 
  closePopupPindan() {
    this.setData({
      hidePindan: true
    })
  },
  // 获取购物车商品数量
  getGoodsNo(){
    let that = this;
    // 获取购物车数据
   
  },

  async getGoodsDetailAndKanjieInfo(goodsId) {
    const that = this;
    const goodsDetailRes = await WXAPI.goodsDetail(goodsId)
    if (goodsDetailRes.retCode == 200) {
      var selectSizeTemp = SelectSizePrefix;
      if (goodsDetailRes.data) {
        that.setData({
          hasMoreSelect: false,
          selectSize: selectSizeTemp,
          selectSizePrice: goodsDetailRes.data.price,
          itemNo: goodsDetailRes.data.itemNo
        });
      }

      let childs = goodsDetailRes.data;
      for (let [index, item] of childs.itemSkuResultDtos.entries()) {
        item.checked = false;
        item.value = index;
        item.text = item.stockTitle;
      }
      // 选中的规格
      childs.itemSkuResultDtos[0].checked = true;
      childs.value = 0; 
      childs.narrowPicUrl = childs.itemSkuResultDtos[0].narrowPicUrl; 
      
      let _data = {
        goodsDetail: goodsDetailRes.data,
        selItem: {
          price: goodsDetailRes.data.itemSkuResultDtos[0].price,
          narrowPicUrl: goodsDetailRes.data.itemSkuResultDtos[0].narrowPicUrl,
          stockTitle: goodsDetailRes.data.itemSkuResultDtos[0].stockTitle,
          stockNo: goodsDetailRes.data.itemSkuResultDtos[0].stockNo,
        },
        selectSizePrice: goodsDetailRes.data.price,
        //totalScoreToPay: goodsDetailRes.data.basicInfo.minScore,
        // buyNumMax: goodsDetailRes.data.stockNum,
        // buyNumber: (goodsDetailRes.data.stockNum > 0) ? 1 : 0
      }
      
       that.setData(_data);
    }
  },
  goShopCar: function() {
    wx.reLaunch({
      url: "/pages/shop-cart/index"
    });
  },
  // 加入购物车，选择数量规格
  toAddShopCar: function() {
    this.setData({
      shopType: "addShopCar"
    })
    this.bindGuiGeTap();
  },
  // 立即购买，选择数量规格
  tobuy: function(e) {
    this.setData({
      hidePindan: true
    })
    // debugger
    let shopNo = e.currentTarget.dataset.shopno || ""
    let groupNo = e.currentTarget.dataset.groupno || ""
    if (e.currentTarget.dataset.type && e.currentTarget.dataset.type === 'single') {

    } else {
      this.setData({
        shopNo,
        groupNo,
        buyType: "pin"// 拼单
      })
    }
    const token = wx.getStorageSync('token') || ""
    // 这里要判断没有登陆还是登陆已经过期
    if (!token) {
      // 未登录
      this.setData({
        showAuthBtn: true
      })
      return
    }
    AUTH.checkHasLogined().then(isLogined => {
      if (!isLogined) {
        // 过期
        wx.login({
          success: loginres => {
            WXAPI.login_wx(loginres.code).then(res => {
              wx.setStorageSync('token', res.data.tokenStr)
              this.setData({
                shopType: "tobuy"
              });
              this.bindGuiGeTap();
            })
          }
        })
      } else {
        const token = wx.getStorageSync('token') || ""
        if (!token) {
          this.setData({
            showAuthBtn: true
          })
          return
        }
        this.setData({
          shopType: "tobuy"
        });
        this.bindGuiGeTap();
      }
    })
  },
  /**
   * 规格选择弹出框
   */
  bindGuiGeTap: function() {
    this.setData({
      hideShopPopup: false
    })
  },
  /**
   * 规格选择弹出框隐藏
   */
  closePopupTap: function() {
    this.setData({
      hideShopPopup: true
    })
  },
  numJianTap: function() {
    if (this.data.buyNumber > this.data.buyNumMin) {
      var currentNum = this.data.buyNumber;
      currentNum--;
      this.setData({
        buyNumber: currentNum
      })
    }
  },
  numJiaTap: function() {
    // if (this.data.buyNumber < this.data.buyNumMax) {
      var currentNum = this.data.buyNumber;
      currentNum++;
      this.setData({
        buyNumber: currentNum
      })
    // }
  },
  /**
   * 选择商品规格
   * @param {Object} e
   */
  labelItemTap: function(e) {
    var that = this;
    let ind = e.currentTarget.dataset.index;
    let childs = that.data.goodsDetail;
    for (let [index ,item] of childs.itemSkuResultDtos.entries()){
      item.checked  = false;
      item.value = index;
      item.text = item.stockTitle;
      if (ind == index){
        childs.stockTitle = item.stockTitle;
        childs.narrowPicUrl = item.narrowPicUrl;
        childs.stockNo = item.stockNo;
        childs.price = item.price;
      }
    }
    // 选中的规格
    childs.itemSkuResultDtos[ind].checked = true;
    childs.value = ind;
    // 购物车选中标识
    childs.checked = false;
    
    that.setData({
      selItem: {
        price: childs.itemSkuResultDtos[ind].price,
        narrowPicUrl: childs.itemSkuResultDtos[ind].narrowPicUrl,
        stockTitle: childs.itemSkuResultDtos[ind].stockTitle,
        stockNo: childs.itemSkuResultDtos[ind].stockNo,
      },
      goodsDetail:childs,
    })

  },
  /**
   * 加入购物车
   */
  addShopCar: function() {
    let that = this;
    let goodsDetailObj = that.data.goodsDetail;
    goodsDetailObj.buyNumber = that.data.buyNumber;
    goodsDetailObj.price = that.data.selItem.price;
    goodsDetailObj.stockNo = that.data.selItem.stockNo;
    goodsDetailObj.stockTitle = that.data.selItem.stockTitle;

    goodsDetailObj.buyMoney = parseFloat(goodsDetailObj.price) * (that.data.buyNumber);
    console.log(goodsDetailObj)
    
    SETGOODS.setGoods(goodsDetailObj, goodsDetailObj.itemNo, that.data.selItem.stockNo, goodsDetailObj.shopNo);
    this.getGoodsNo();

    // 写入本地存储
    
    this.closePopupTap();
    wx.showToast({
      title: '加入购物车成功',
      icon: 'success',
      duration: 2000,
      success(){
        that.setData({
          shopNum: app.globalData.goodsNo,
        })
      }
    })
  },
  // 检查当前拼团订单状态
  async checkIsJoinPindan() {    
    await WXAPI.checkPindan(this.data.groupNo).then(res => {
      if ((res.retCode - 0) === 3000) {
        wx.redirectTo({
          url: '/pages/order-list/index',
        })
      }
      else if ((res.retCode - 0) !== 200) {
       wx.showToast({
         title: res.retMsg,
         icon: "none"
       })
       this.setData({
         bool: 0
       })
     } else {
      this.setData({
        bool: 1
      })
     }
    })
  },
  /**
   * 立即购买
   */
  async buyNow (e) {
    if (this.data.groupNo) {
      await this.checkIsJoinPindan()
      if (!this.data.bool) {
        this.closePopupTap()
        return
      }
    }
    let that = this
    let shoptype = e.currentTarget.dataset.shoptype
    //组建立即购买信息
    let goodsDetailObj = that.data.goodsDetail;
    goodsDetailObj.buyNumber = that.data.buyNumber;
    goodsDetailObj.price = that.data.selItem.price;
    goodsDetailObj.stockNo = that.data.selItem.stockNo;
    goodsDetailObj.stockTitle = that.data.selItem.stockTitle;
    goodsDetailObj.checked = true;

    goodsDetailObj.buyMoney = parseFloat(goodsDetailObj.price) * (that.data.buyNumber);
    // console.log(goodsDetailObj)

    let resArr = [{
      shopNo: goodsDetailObj.shopNo,
      shopName: goodsDetailObj.shopName,
      checked: false,
      list: []
    }]
    // console.log(goodsObj)
    goodsDetailObj.buyMoney = parseFloat(goodsDetailObj.price) * goodsDetailObj.buyNumber;
    resArr[0].list.push(goodsDetailObj);

    SETGOODS.setBuyNowGoods(resArr);
    this.closePopupTap();
    wx.navigateTo({
      url: `/pages/to-pay-order/index?orderType=buyNow&groupNo=${this.data.groupNo}`
    })

  },


  /**
   * 组建购物车信息
   */
  bulidShopCarInfo: function() {
    // 加入购物车
    var shopCarMap = {};
    shopCarMap.goodsId = this.data.goodsDetail.itemNo;
    shopCarMap.pic = this.data.goodsDetail.narrowPicUrl;
    shopCarMap.name = this.data.goodsDetail.itemTitle;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;
    //shopCarMap.logisticsType = this.data.goodsDetail.basicInfo.logisticsId;
    //shopCarMap.logistics = this.data.goodsDetail.logistics;
    //shopCarMap.weight = this.data.goodsDetail.basicInfo.weight;

    var shopCarInfo = this.data.shopCarInfo;
    if (!shopCarInfo.shopNum) {
      shopCarInfo.shopNum = 0;
    }
    if (!shopCarInfo.shopList) {
      shopCarInfo.shopList = [];
    }
    var hasSameGoodsIndex = -1;
    for (var i = 0; i < shopCarInfo.shopList.length; i++) {
      var tmpShopCarMap = shopCarInfo.shopList[i];
      if (tmpShopCarMap.goodsId == shopCarMap.goodsId && tmpShopCarMap.propertyChildIds == shopCarMap.propertyChildIds) {
        hasSameGoodsIndex = i;
        shopCarMap.number = shopCarMap.number + tmpShopCarMap.number;
        break;
      }
    }

    shopCarInfo.shopNum = shopCarInfo.shopNum + this.data.buyNumber;
    if (hasSameGoodsIndex > -1) {
      shopCarInfo.shopList.splice(hasSameGoodsIndex, 1, shopCarMap);
    } else {
      shopCarInfo.shopList.push(shopCarMap);
    }
    shopCarInfo.kjId = this.data.kjId;

    return shopCarInfo;
  },
  /**
   * 组建立即购买信息
   */
  buliduBuyNowInfo: function(shoptype) {
    var shopCarMap = {};
    console.log("buliduBuyNowInfo data=", this.data)
    shopCarMap.goodsId = this.data.goodsDetail.itemNo;
    shopCarMap.pic = this.data.goodsDetail.picUrl;
    shopCarMap.name = this.data.goodsDetail.itemTitle;
    // shopCarMap.label=this.data.goodsDetail.basicInfo.id; 规格尺寸 
    shopCarMap.propertyChildIds = this.data.propertyChildIds;
    shopCarMap.label = this.data.propertyChildNames;
    shopCarMap.price = this.data.selectSizePrice;
    // if (shoptype == 'toPingtuan') { // 20190714 拼团价格注释掉
    //   shopCarMap.price = this.data.goodsDetail.basicInfo.pingtuanPrice;
    // }
    shopCarMap.score = this.data.totalScoreToPay;
    shopCarMap.left = "";
    shopCarMap.active = true;
    shopCarMap.number = this.data.buyNumber;

    var buyNowInfo = {};
    if (!buyNowInfo.shopNum) {
      buyNowInfo.shopNum = 0;
    }
    if (!buyNowInfo.shopList) {
      buyNowInfo.shopList = [];
    }

    buyNowInfo.shopList.push(shopCarMap);
    buyNowInfo.kjId = this.data.kjId;
    return buyNowInfo;
  },
  onShareAppMessage: function() {
    let _data = {
      title: this.data.goodsDetail.itemTitle,
      path: '/pages/goods-details/index?id=' + this.data.goodsDetail.itemNo + '&shopNo=' + wx.getStorageSync('shopNo'),
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
    // if (this.data.kjJoinUid) {
    //   _data.title = this.data.curKanjiaprogress.joiner.nick + '邀请您帮TA砍价'
    //   _data.path += '&kjJoinUid=' + this.data.kjJoinUid
    // }
    return _data
  },
  reputation: function(goodsId) {
    var that = this;
    WXAPI.goodsReputation({
      goodsId: goodsId
    }).then(function(res) {
      if (res.code == 0) {
        that.setData({
          reputation: res.data
        });
      }
    })
  },
  pingtuanList: function(goodsId) {
    var that = this;
    WXAPI.pingtuanList({
      goodsId: goodsId,
      status: 0
    }).then(function(res) {
      if (res.code == 0) {
        that.setData({
          pingtuanList: res.data.result
        });
      }
    })
  },
  getVideoSrc: function(videoId) {
    var that = this;
    WXAPI.videoDetail(videoId).then(function(res) {
      if (res.code == 0) {
        that.setData({
          videoMp4Src: res.data.fdMp4
        });
      }
    })
  },
  joinKanjia(){
    AUTH.checkHasLogined().then(isLogined => {
      if (isLogined) {
        this.doneJoinKanjia();
      } else {
        wx.showModal({
          title: '提示',
          content: '本次操作需要您的登录授权',
          cancelText: '暂不登录',
          confirmText: '前往登录',
          success(res) {
            if (res.confirm) {
              wx.switchTab({
                url: "/pages/my/index"
              })
            }
          }
        })
      }
    })
  },
  goIndex() {
    wx.switchTab({
      url: '/pages/index/index',
    });
  }
})